package com.wontube.smr.web.controller.i18n;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.wontube.client.modle.vo.PagenateInfo;
import com.wontube.client.remote.Remoting;
import com.wontube.smr.client.model.po.Movie;
import com.wontube.smr.client.model.po.TVEpisode;
import com.wontube.smr.client.model.po.TVShow;
import com.wontube.smr.client.model.vo.MovieItems;
import com.wontube.smr.client.model.vo.TVShowItems;
import com.wontube.smr.web.client.IAnimeWebHandler;
import com.wontube.smr.web.client.IFeaturesHandler;
import com.wontube.smr.web.client.ITVWebHandler;
import com.wontube.smr.web.client.model.bo.QueryItemParams;

@Controller
@RequestMapping("/world/featured")
public class I18nFeaturedController {
	private final static int PAGE_SIZE = 30;
	private final static String TODAY_PERIOD = "today";
	
	@RequestMapping("")
	public void f1(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/world/featured/");		
	}
	
	@RequestMapping("/")
	public ModelAndView featuredHome() {
		return youtubeFeatureds();
	}
	
	@RequestMapping("/youtube")
	public void f2(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
		response.sendRedirect(request.getContextPath() + "/world/featured/youtube/");		
	}

	@RequestMapping("/youtube/")
	public ModelAndView youtubeFeatureds() {
		ModelAndView mv = listYoutubeMostVieweds(null, null, null, true);
		mv.setViewName("i18n/featured/featured_index");
		return mv;
	}
	
	@RequestMapping("/youtube/query")
	public ModelAndView listYoutubes(@RequestParam(value="period", required=false) String period, 
			@RequestParam(value="genre", required=false) String genre, 
			@RequestParam(value="page", required=false) Integer page){
		ModelAndView mv = listYoutubeMostVieweds(period, genre, page, false);
		mv.setViewName("i18n/featured/youtube_list");	
		return mv;
	}
	
	@RequestMapping("/youtube/relate/{id}")
	public ModelAndView youtubeRelated(@PathVariable("id") String id) {
		IFeaturesHandler handler = getIFeaturesHandler();
		MovieItems items = handler.listRelated(id, new PagenateInfo(1, 5));
		ModelAndView mv = new ModelAndView("i18n/featured/play/youtube_relate_video");
		mv.addObject("movieItems", items);
		return mv;
	}
	
	@RequestMapping("/youtube/{id}")
	public ModelAndView youtubeDetail(@PathVariable("id") String id,
			HttpServletResponse response) throws IOException {
		IFeaturesHandler handler = getIFeaturesHandler();
		Movie movie = handler.getShortFilm(id);
		if (movie == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			ModelAndView mv = new ModelAndView("i18n/featured/detail/youtube_detail_index");
			mv.addObject("show", movie);
			return mv;
		}
	}
	
	@RequestMapping("/youtube/watch-{id}")
	public ModelAndView playYoutube(@PathVariable("id") String id,
			HttpServletResponse response) throws IOException {
		IFeaturesHandler handler = getIFeaturesHandler();
		Movie movie = handler.getShortFilm(id);
		if (movie == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			ModelAndView mv = new ModelAndView("i18n/featured/play/youtube_play");
			mv.addObject("show", movie);
			return mv;
		}
	}
	
	@RequestMapping("/chtv")
	public ModelAndView getChineseTV(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page){
		ModelAndView mv = getCrunchyrollTV("chinese", 1, "i18n/featured/crunchyroll/crunchyroll_index");
		return mv;
	}
	
	@RequestMapping("/jptv")
	public ModelAndView getJapaneseTV(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page){
		ModelAndView mv = getCrunchyrollTV("japanese", 1, "i18n/featured/crunchyroll/crunchyroll_index");
		return mv;
	}
	
	@RequestMapping("/krtv")
	public ModelAndView getKoreaTV(@RequestParam(value="page", required=false, defaultValue="1") Integer page){
		ModelAndView mv = getCrunchyrollTV("korea", 1, "i18n/featured/crunchyroll/crunchyroll_index");
		return mv;
	}
	
	@RequestMapping("/othertv")
	public ModelAndView getSurprise(@RequestParam(value="page", required=false, defaultValue="1") Integer page){
		ModelAndView mv = getCrunchyrollTV("surprise", 1, "i18n/featured/crunchyroll/crunchyroll_index");
		return mv;
	}
	
	@RequestMapping("/tv/query")
	public ModelAndView queryTVShow(@RequestParam(value="category") String category,
			@RequestParam(value="page") Integer page){
		ModelAndView mv = getCrunchyrollTV(category, page, "i18n/featured/crunchyroll/crunchyroll_content");
		return mv;
	}
	
	@RequestMapping("/tv/{id}")
	public ModelAndView getCrunchyrollTVDetail(@PathVariable("id") String showId){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("i18n/featured/detail/crunchyroll_detail_index");
		IAnimeWebHandler animeWebHandler = getAnimeWebHandler();
		Map<String, Object> maps = animeWebHandler.collectTVDetails(showId);
		mv.addAllObjects(maps);
		return mv;
	}
	
	@RequestMapping("/tv/watch-{id}")
	public ModelAndView playCrunchyrollTV(@PathVariable("id") String id){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("i18n/featured/play/crunchyroll_play_index");
		IAnimeWebHandler animeWebHandler = getAnimeWebHandler();		
		Map<String, Object> maps = animeWebHandler.collectTVPlayDetail(id);
		TVEpisode ep = (TVEpisode)maps.get("anime");
		if(ep != null){
			String url = ep.getUrl();
			String[] urlAry = url.split("-");		
			mv.addObject("mediaid",urlAry[urlAry.length-1]);
		}
		
		mv.addAllObjects(maps);
		return mv;
	}
	
	@RequestMapping("/tv/relate/")
	public ModelAndView getRelateAnime(@RequestParam("category") String category,@RequestParam("showId") String showId){
		TVShowItems items = new TVShowItems();
		Remoting<ITVWebHandler> remoting = new Remoting<ITVWebHandler>();
		ITVWebHandler tvWebHandler = remoting.createService(ITVWebHandler.class);
		if("chinese".equals(category)){
			items = tvWebHandler.listChineseTVShows(new PagenateInfo(1, 6));
		}else if("japanese".equals(category)){
			items = tvWebHandler.listJapaneseTVShows(new PagenateInfo(1, 6));
		}else if("korea".equals(category)){
			items = tvWebHandler.listKoreaTVShows(new PagenateInfo(1,6));
		}else{
			items = tvWebHandler.listSurpriseDramaTVShows(new PagenateInfo(1,6));
		}
		List<TVShow> list = new ArrayList<TVShow>();
		for (TVShow tvshow : items.getItems()) {
			if (!tvshow.getId().equals(showId) && list.size() < 5) {
				list.add(tvshow);
			}
		}
		items.setItems(list);
		ModelAndView mv = new ModelAndView("i18n/featured/play/crunchyroll_relate_tv");
		mv.addObject("showItems", items);
		return mv;
	}
	
	private ModelAndView getCrunchyrollTV(String category,Integer page,String viewName){
		ModelAndView mv = new ModelAndView(viewName);
		Remoting<ITVWebHandler> remoting = new Remoting<ITVWebHandler>();
		ITVWebHandler tvWebHandler = remoting.createService(ITVWebHandler.class);
		TVShowItems items = null;
		if("chinese".equals(category)){
			items = tvWebHandler.listChineseTVShows(new PagenateInfo(page,PAGE_SIZE));
		}else if("japanese".equals(category)){
			items = tvWebHandler.listJapaneseTVShows(new PagenateInfo(page, PAGE_SIZE));
		}else if("korea".equals(category)){
			items = tvWebHandler.listKoreaTVShows(new PagenateInfo(page, PAGE_SIZE));
		}else{
			items = tvWebHandler.listSurpriseDramaTVShows(new PagenateInfo(page, PAGE_SIZE));
		}
		if(items != null){
			if(items.getItems().size() == PAGE_SIZE){
				mv.addObject("hasMore", true);
			}
		}
		mv.addObject("showItems", items);
		mv.addObject("category", category);
		return mv;
	}
	
	private ModelAndView listYoutubeMostVieweds(String period, String genre, Integer page, boolean needGenres){
		if(page == null || page.intValue() < 1){
			page = 1;
		}		
		if(period == null){
			period = TODAY_PERIOD;
		}
		QueryItemParams params = new QueryItemParams();
		params.setGenre(genre);
		params.setPeriod(period);
		params.setNeedGenres(needGenres);
		
		IFeaturesHandler handler = getIFeaturesHandler();
		MovieItems movieItems = handler.listYoutubeMostViewed(params, new PagenateInfo(page, PAGE_SIZE));
		ModelAndView mv = new ModelAndView();
		if(needGenres && movieItems != null){
			mv.addObject("genres", movieItems.getGenres());
		}
		mv.addObject("movieItems", movieItems);
		mv.addObject("page", page);
		mv.addObject("period", period);
		return mv;
	}
	
	private IFeaturesHandler getIFeaturesHandler() {
		Remoting<IFeaturesHandler> remoting = new Remoting<IFeaturesHandler>();
		return remoting.createService(IFeaturesHandler.class);
	}
	
	private IAnimeWebHandler getAnimeWebHandler() {
		Remoting<IAnimeWebHandler> remoting = new Remoting<IAnimeWebHandler>();
		return remoting.createService(IAnimeWebHandler.class);
	}
}
